package pool;

import configuration.MyConfiguration;
import http.MyHttpRequest;
import http.MyHttpResponse;
import util.HttpUtil;
import util.MyUtil;

import java.io.*;

/**
 * @author Karl
 * @Date 2023/1/1 - 19:56
 */
public class TaskFactory {

    private TaskFactory(){}


    public static Runnable replaceFile(MyHttpRequest request, MyHttpResponse askResponse) {
        return () -> {
            try {
                Thread.sleep(50);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            OutputStream os = null;
            File file = new File(MyConfiguration.getFileRoot() + request.getUrl());
            File tempFile = new File(MyConfiguration.getFileRoot() + request.getUrl()+".tmp");
            try {
                os = new FileOutputStream(tempFile);
                HttpUtil.writeToFile(askResponse,os);
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }finally {
                MyUtil.closeIo(os);
            }
            int cnt = 0 ;
            while(cnt<10){
                if (file.delete()) {
                    break;
                }
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                cnt++;
            }
            if(cnt==10) return;
            cnt =0 ;
            while(cnt<10){
                if (tempFile.renameTo(file)) {
                    break;
                }
                try {
                    Thread.sleep(50);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                cnt++;
            }
        };
    }
}
